package com.tuanzi.loan.business.repository.statistics.impl;

import com.tuanzi.loan.business.repository.statistics.ActivityAverageJoinStatRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.vo.request.statistics.ActivityAverageJoinStatRequest;
import com.tuanzi.loan.vo.response.statistics.ActivityAverageJoinStatResponse;
import org.jooq.Condition;
import org.jooq.GroupField;
import org.jooq.SelectField;
import org.jooq.SelectQuery;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.tuanzi.loan.generated.jooq.loan.tables.CommProductPrdid.COMM_PRODUCT_PRDID;
import static com.tuanzi.loan.generated.jooq.loan.tables.UmengActiveRecord.UMENG_ACTIVE_RECORD;

@Repository
public class ActivityAverageJoinStatRepositoryImpl extends JOOQBaseRepositoryPlus implements ActivityAverageJoinStatRepository{

	private static final String ALL_FIELD_ID = "'-1000'";
	private static final String ALL_FIELD = "'全部'";

	@Override
	protected TableImpl getTable() {
		return UMENG_ACTIVE_RECORD;
	}

	@SuppressWarnings("unchecked")
	public Page<ActivityAverageJoinStatResponse> getListByAverageJoin(ActivityAverageJoinStatRequest searchRequest) {
		Condition condition = DSL.trueCondition();
        List<SelectField<?>> selectFields = new ArrayList<>();
        List<GroupField> groupFields = new ArrayList<>();

        selectFields.add(UMENG_ACTIVE_RECORD.ACTIVE_DATE);
        groupFields.add(UMENG_ACTIVE_RECORD.ACTIVE_DATE);

        if (Objects.nonNull(searchRequest.getStartDate())) {
            condition = condition.and(UMENG_ACTIVE_RECORD.ACTIVE_DATE.ge(new java.sql.Date(searchRequest.getStartDate().getTime())));
        }
        if (Objects.nonNull(searchRequest.getEndDate())) {
        	condition = condition.and(UMENG_ACTIVE_RECORD.ACTIVE_DATE.le(new java.sql.Date(searchRequest.getEndDate().getTime())));
        }

        // 产品
        if (Objects.isNull(searchRequest.getProductId()) || searchRequest.getProductId().isEmpty()) {
        	// 全部展开
        	selectFields.add(UMENG_ACTIVE_RECORD.PRDID);
			selectFields.add(COMM_PRODUCT_PRDID.PARENT_ID);
            groupFields.add(UMENG_ACTIVE_RECORD.PRDID);
        } else if(searchRequest.getParentIdList().size() > 0) {
        	// 按照大产品分组
			selectFields.add(UMENG_ACTIVE_RECORD.PRDID);
			selectFields.add(COMM_PRODUCT_PRDID.PARENT_ID);
			groupFields.add(COMM_PRODUCT_PRDID.PARENT_ID);
			condition = condition.and(COMM_PRODUCT_PRDID.PARENT_ID.in(searchRequest.getParentIdList()));
        } else {
            selectFields.add(UMENG_ACTIVE_RECORD.PRDID);
			selectFields.add(COMM_PRODUCT_PRDID.PARENT_ID);
            groupFields.add(UMENG_ACTIVE_RECORD.PRDID);
            condition = condition.and(UMENG_ACTIVE_RECORD.PRDID.in(searchRequest.getProductId()));
        }

        // 平台
        if (Objects.isNull(searchRequest.getPlatform()) || searchRequest.getPlatform().isEmpty()) {
        	// 全部展开
        	selectFields.add(UMENG_ACTIVE_RECORD.PLATFORM);
            groupFields.add(UMENG_ACTIVE_RECORD.PLATFORM);
        } else if(isSelectQueryAll(searchRequest.getPlatform())) {
        	// 查询全部
        	selectFields.add(DSL.field(ALL_FIELD_ID).as("platform"));
        } else {
            selectFields.add(UMENG_ACTIVE_RECORD.PLATFORM);
            groupFields.add(UMENG_ACTIVE_RECORD.PLATFORM);
            condition = condition.and(UMENG_ACTIVE_RECORD.PLATFORM.in(searchRequest.getPlatform()));
        }

        SelectQuery selectQuery = dslContext.select(selectFields)
        		.select(DSL.field(ALL_FIELD_ID).as("is_newuser"))
                .select(DSL.sum(UMENG_ACTIVE_RECORD.ACTIVE_NUM).as("active_num"))
                .select(DSL.sum(UMENG_ACTIVE_RECORD.INSTALL_NUM).as("install_num"))
                .from(UMENG_ACTIVE_RECORD)
				.leftJoin(COMM_PRODUCT_PRDID)
				.on(UMENG_ACTIVE_RECORD.PRDID.eq(COMM_PRODUCT_PRDID.PRDID.cast(String.class)))
                .where(condition)
                .groupBy(groupFields)
                .orderBy(UMENG_ACTIVE_RECORD.ACTIVE_DATE.desc())
                .getQuery();

        List<ActivityAverageJoinStatResponse> resultList = selectQuery.fetch(record -> {
            ActivityAverageJoinStatResponse response = new ActivityAverageJoinStatResponse();
            response.setDate(record.get(0, Date.class));
			if(searchRequest.getParentIdList().size() > 0){
				response.setProductId("-1000");
			}else{
				response.setProductId(record.get(1,String.class));
			}
            response.setParentId(record.get(2, String.class));
            response.setPlatform(record.get(3, String.class));
            response.setUserType(record.get(4, String.class));
            response.setActivity_uv(record.get(5, Integer.class));
            response.setInstall_uv(record.get(6, Integer.class));
            return response;
        });

        // 计算新老用户
        if(!isSelectQueryAll(searchRequest.getUserType()) && resultList != null) {
        	List<ActivityAverageJoinStatResponse> newList = new ArrayList<ActivityAverageJoinStatResponse>();
        	for(ActivityAverageJoinStatResponse result : resultList) {
        		ActivityAverageJoinStatResponse newResponse = new ActivityAverageJoinStatResponse();
        		newResponse.setDate(result.getDate());
        		newResponse.setProductId(result.getProductId());
        		newResponse.setParentId(result.getParentId());
        		newResponse.setUserType("1");
        		newResponse.setPlatform(result.getPlatform());
        		newResponse.setActivity_uv(result.getInstall_uv());

        		ActivityAverageJoinStatResponse oldResponse = new ActivityAverageJoinStatResponse();
        		oldResponse.setDate(result.getDate());
        		oldResponse.setProductId(result.getProductId());
				oldResponse.setParentId(result.getParentId());
        		oldResponse.setUserType("0");
        		oldResponse.setPlatform(result.getPlatform());
        		oldResponse.setActivity_uv(result.getActivity_uv() - result.getInstall_uv());

        		newList.add(result);
        		newList.add(oldResponse);
        		newList.add(newResponse);
        	}
        	resultList = newList;
        }

		return new PageImpl<ActivityAverageJoinStatResponse>(resultList);
	}


	/******检查是否查询全部*********/
    private boolean isSelectQueryAll(List selectList) {
    	if(selectList == null || selectList.size() == 0) {
    		return false;
    	}
    	for(int i=0; i<selectList.size(); i++) {
    		String s = String.valueOf(selectList.get(i));
    		if("-1000".equals(s)) {
    			return true;
    		}
    	}
    	return false;
    }

}
























